package com.zc.serviceuser.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zc.exceptionhandler.ZcException;
import com.zc.serviceuser.entity.User;
import com.zc.serviceuser.service.impl.UserServiceImpl;
import com.zc.serviceuser.user.ReadUser;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ExcelListener extends AnalysisEventListener<ReadUser> {

    private UserServiceImpl userService;

    public ExcelListener(UserServiceImpl userService) {
        this.userService = userService;
    }


    public ExcelListener() {
    }

    @Override
    public void invoke(ReadUser readUser, AnalysisContext analysisContext) {
        System.out.println(readUser);
        if (readUser==null){
            throw  new ZcException(400,"文件为空");
        }

        //将结果放到map中，减少数据库压力
        List<User> list = userService.list();
        Map<String, String> map = list.stream().collect(Collectors.toMap(User::getPhone, User::getPassword));

        String oneUser = map.get(readUser.getPhone());
        if (oneUser==null){
            User user = new User();
            user.setUserName(readUser.getUserName());
            user.setPhone(readUser.getPhone());
            user.setPassword(readUser.getPassword());
            user.setDescription(readUser.getDescription());
            userService.save(user);
        }

    }
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
